package com.enjoyor.health.HGPT.web.rest;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONObject;
import com.enjoyor.health.HGPT.core.config.ParamConfig;
import com.enjoyor.health.HGPT.core.dto.RobotKnowledgeBaseDto;
import com.enjoyor.health.HGPT.core.entity.UserInfo;
import com.enjoyor.health.HGPT.core.service.IHealthIndicatorInfoService;
import com.enjoyor.health.HGPT.core.service.IUserInfoService;
import com.enjoyor.health.HGPT.service.BizReportService;
import com.enjoyor.health.HGPT.web.CodeEnum;
import com.enjoyor.health.HGPT.web.RetResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Zhu Min
 * @date 2023/10/23 19:10
 */
@Api(value = "报告", tags = {"报告"})
@Slf4j
@RestController
public class ReportController {

    @Autowired
    private BizReportService bizReportService;
    @Autowired
    private ParamConfig paramConfig;
    @Autowired
    private IUserInfoService userInfoService;


    /**
     * # 编写 SQL 查询语句，根据 user_id 和 version 在 report_record 表中获取对应的 report_id。
     * # 编写 SQL 查询语句，根据 report_id 在 report_data 表中获取所有数据。
     * # 编写 SQL 查询语句，查询 user_info 表中的 name、age 和 gender 字段。
     * # 根据 user_id 和 version 在 report_record 表中获取 update_time 字段。
     * # 根据 user_id 和 version 在 report_record 表中统计该用户的报告数量。
     * # 编写 Python 代码，将表 A、B 和 C 关联起来，并按照 body_part_name 分组，遍历每个分组，计算 organ、result 和 advice 字段。
     * # 构造返回结果，并返回给前端。
     * # 获取指定用户指定版本的所有检查部位和对应的器官名称
     */
    @RequestMapping(value = "/aiHealthReport/medicalReportShow", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult showMedicalReport(String openId, String version, String type, @RequestParam(defaultValue = "1") String packageType){
        if (StringUtils.isBlank(openId)){
            return new RetResult().of(CodeEnum.MISS_CODE);
        }
        Integer pType = null;
        try {
            pType = Integer.parseInt(packageType);
        }catch (Exception e){
            log.warn("packageType is {}", packageType);
            pType = 1;
        }

        JSONObject o = bizReportService.getMedicalReportData(openId, version, type, pType);
        if (o.size() == 0){
            return new RetResult(CodeEnum.NO_USER_INFO);
        }else {
            return new RetResult().setResult(o);
        }
    }

    @RequestMapping(value = "/aiHealthReport/medicalReportDetail", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult showMedicalReportDetailedValue(String openId, String organ, String version){
        return new RetResult().setResult(bizReportService.getMedicalReportDataDetail(openId, organ, version));
    }

    //TODO 报告PDF
    @RequestMapping(value = "/aiHealthReport/generateMedicalReportPDF", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult generateMedicalReportPdf(){
        return null;
    }

    @RequestMapping(value = "/aiHealthReport/vitalSignsShow", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult showVitalSignsValue(String openId, String organ, String version){
        return new RetResult().setResult(bizReportService.getMedicalReportDataDetail(openId, organ, version));
    }

    /**
     * 生命体征数据
     */
    @RequestMapping(value = "/aiHealthReport/vitalSignsDetail", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult showVitalSignsDetailedValue(String openId, String startDate, String endDate, String signType, String dateType){
        return new RetResult().setResult(bizReportService.showVitalSignsDetail(openId, startDate, endDate, signType, dateType));
    }

    @RequestMapping(value = "/aiHealthReport/medicalReportDownload", method = { RequestMethod.GET, RequestMethod.POST })
    public void downloadReport(String version, String openId, HttpServletResponse response){
        try {
            String path  = bizReportService.reportDownload(openId, version);
            File file = new File(path);
            ServletOutputStream outputStream = response.getOutputStream();
            response.addHeader("Content-Disposition", "attachment;filename =" + URLEncoder.encode(file.getName(), "UTF-8"));
            response.setContentType("application/octet-stream");
            byte[] bytes = FileUtil.readBytes(file);
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
            log.error("报告下载出错", e);
        }
    }

    @RequestMapping(value = "/aiHealthReport/pdfSave", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult pdfSave(@RequestParam MultipartFile file, HttpServletRequest request){
        try {
            String path = paramConfig.getReportUrl() + file.getOriginalFilename();
            file.transferTo(new File(path));
            return new RetResult();
        }catch (IOException e){
            log.error("报告文件接收出错", e);
            return new RetResult(CodeEnum.SERVER_EXCEPTION);
        }
    }

    /**
     * 机器人报告列表
     * @param openId
     * @param version
     * @return
     */
    @RequestMapping(value = "/aiHealthReport", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult healthReport(String openId, String version, String packageType){
        if (StringUtils.isBlank(openId)){
            return new RetResult().of(CodeEnum.MISS_CODE);
        }
        JSONObject o;
        if ("3".equals(packageType)){
            o = bizReportService.getHealthReportDataV2(openId, version);
        }else {
            o = bizReportService.getHealthReportData(openId, version);
        }
        if (o.size() == 0){
            return new RetResult(CodeEnum.NO_USER_INFO);
        }else {
            return new RetResult().setResult(o);
        }
    }

    /**
     * 机器人报告详情
     * @param openId
     * @param partNameEn
     * @param version
     * @param packageType 全身筛查的时候传递参数3
     * @return
     */
    @RequestMapping(value = "/aiHealthReportDetail", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult healthReportRobotDetailedValue(String openId, String partNameEn, String version, String packageType){
        return new RetResult().setResult(bizReportService.getReportDataRobotDetail(openId, partNameEn, version, packageType));
    }

    /**
     * 获取指标范围
     */
    @RequestMapping(value = "/aiHealthReport/healthIndicator", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult getHealthIndicator(String name, String openId){
        UserInfo userInfo = userInfoService.getUserInfoFromOpenId(openId);
        if ("uricAcid".equals(name) ){
            if (userInfo == null){
                return new RetResult(CodeEnum.NO_USER_INFO);
            }else {
                return new RetResult().setResult(
                        bizReportService.getHealthIndicatorList().stream().filter(x->name.equals(x.getName()) &&
                                ((userInfo.getGender() != null && userInfo.getGender()==1)?"female":"male").equals(x.getRemark())).collect(Collectors.toList())
                );
            }
        }
        return new RetResult().setResult(bizReportService.getHealthIndicatorList().stream().filter(x->name.equals(x.getName())).collect(Collectors.toList()));
    }


}
